package lucene.server.database.executor;


import lucene.server.database.utils.DatabaseUtil;
import lucene.server.database.utils.ResultSetUtil;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class SqlExecutor {

    public static List<Map<String,Object>> query(Connection connection, String sql, Object... params) throws SQLException {

        PreparedStatement ps = connection.prepareStatement(sql);
        ResultSet rs = ps.executeQuery();
        if (params != null && params.length > 0) {
            for (int i = 0; i < params.length; i++) {
                ps.setObject(i + 1, params[i]);
            }
        }
        ResultSetMetaData metaData = rs.getMetaData();
        List<Map<String,Object>> list =  new ArrayList<>();
        while (rs.next()) {
            list.add(ResultSetUtil.toMap(metaData,rs));
        }
        DatabaseUtil.close(rs,ps);
        return list;
    }


}
